<?

  error_reporting(E_ALL);
  ini_set('display_errors', 1);

include_once 'controller.inc.php';
include_once 'event_helper.inc.php';

$id = $_POST['id'];
$owner = $_POST['owner'];
$name = $_POST['name'];
$description = $_POST['description'];
$location = $_POST['location'];

$event_times = getDateTimesFromRequest($_POST);
$start_time = $event_times[0];
$end_time = $event_times[1];

$db_link = db_connect();
$event = db_getEvent($id);

// overkill role creation - trying to minimize id growth
$new_roles = array();
$old_roles = db_getRolesForEvent($event);

// get roles from form submission, ignoring duplicates
$idx = 1;
foreach ($_POST as $key => $val) {
  if (preg_match('/role(?P<num>\d+?)_name/', $key, $role_num) > 0) {
    $role_num = $role_num['num'];
    $role_name = $_POST[$key];
    $role_user_id = $_POST['role'.$role_num.'_user'];
    
    $valid = TRUE;
    foreach ($new_roles as $added_role) {
      if ($added_role->getName() == $role_name && $added_role->getUserID() == $role_user_id) {
        $valid = FALSE;
      }
    }
    if ($valid && !empty($role_name)) {
      $role = new Role();
      $role->setName($role_name);
      $role->setUser($role_user_id);
      $role->setEvent($id);
      $new_roles[$idx++] = $role;
    }
  }
}

// see which old roles we can keep (don't add, don't delete)
foreach ($old_roles as $i => $old_role) {
  $old_role_name = $old_role->getName();
  $old_role_user_id = $old_role->getUserID();
  foreach ($new_roles as $j => $new_role) {
    if ($old_role_name == $new_role->getName() && $old_role_user_id == $new_role->getUserID()) {
      unset($old_roles[$i]);
      unset($new_roles[$j]);
      break;
    }
  }
}

// see which old roles we can edit (and go ahead and edit them, don't add/delete)
foreach ($old_roles as $i => $old_role) {
  $old_role_name = $old_role->getName();
  foreach ($new_roles as $j => $new_role) {
    if ($old_role_name == $new_role->getName()) {
      $old_role->setUser($new_role->getUserID());
      db_updateRole($old_role);
      unset($old_roles[$i]);
      unset($new_roles[$j]);
      break;
    }
  }
}

// delete old roles
foreach ($old_roles as $old_role) {
  db_deleteRole($old_role);
}

// create new roles
foreach ($new_roles as $new_role) {
  db_createRole($new_role);
}

// back to event stuff
$event->setName($name);
if ($owner != 0) $event->setOwner($owner);
$event->setDescription($description);
$event->setLocation($location);
$event->setStartTime($start_time);
$event->setEndTime($end_time);
db_updateEvent($event);

db_disconnect($db_link);

header('Location: view_event.php?id='.$id.'&success=Event_updated');

?>
